<?php

namespace Yongf\Utils;

/**
 * 文本相关
 */
class UText
{

    /**
     * @Description：字符串截取，中英文
     * @Docs：
     *
     * @param $str
     * @param $start
     * @param $length
     * @param $charset
     * @param $suffix
     *
     * @return mixed|string
     * @Author：雍飞
     * @Date：2022/6/23 11:25
     */
    public static function cSubstr($str, $start, $length, $charset = "utf-8", $suffix = "")
    {
        if (function_exists("mb_substr")) {
            $slice = mb_substr($str, $start, $length, $charset);
        } else {
            $re['utf-8']  = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
            $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
            $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
            $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
            preg_match_all($re[$charset], $str, $match);
            if (count($match[0]) <= $length) {
                return $str;
            }
            $slice = join("", array_slice($match[0], $start, $length));
        }
        return $slice . $suffix;
    }


    /**
     * @Description：以什么开头
     * @Docs：
     *
     * @param $str
     * @param $pattern
     *
     * @return bool
     * @Author：雍飞
     * @Date：2022/6/23 14:54
     */
    public static function startWith($str, $pattern): bool
    {
        return strpos($str, $pattern) === 0;
    }

    /**
     * @Description： 下划线转驼峰
     * @Docs：
     *
     * @param $string
     *
     * @return array|string|string[]|null
     * @Author：雍飞
     * @Date：2022/6/23 14:50
     */
    public static function underline2Camel($string)
    {
        if (empty($string)) {
            return $string;
        }
        return preg_replace_callback('/_(\w)/', function ($mat) {
            return strtoupper($mat[1]);
        }, $string);
    }

    /**
     * @Description：驼峰转下划线
     * @Docs：
     *
     * @param $string
     *
     * @return string
     * @Author：雍飞
     * @Date：2022/6/23 14:50
     */
    public static function camel2Underline($string): string
    {
        if (empty($string)) {
            return $string;
        }
        $str = strtolower(substr(preg_replace('#[A-Z]#', '_$0', $string), 0));
        if (self::startWith($str, "_")) {
            return ltrim($str, '_');
        }
        return $str;
    }

}